<template>
  <div class="app-single-image-upload" :style="{height: `${108 + (size ? 26 : 0)}px`}">
    <span class="el-upload__tip" v-if="size">建议尺寸：{{size}}像素</span>
    <el-upload list-type="picture-card"
               :limit="1"
               :action="url"
               :http-request="upload"
               :on-success="onSuccess"
               :on-remove="onRemove"
               :file-list="fileList"
               :show-file-list="true"
               :disabled="disabled"
               accept="image/jpeg,image/png,image/gif"
               name="multipartFile">
      <i class="el-icon-plus"></i>
    </el-upload>
    <!-- <span style="color: red; line-height: 16px;" class="el-upload__tip" :style="{opacity: required && !value ? 1 : 0}">该图片是必须的</span> -->
  </div>
</template>

<script>
  import axios from 'axios'

  export default {
    name:'AppSingleImageUpload',
    props: {
      value: String,
      urlProp: String,
      disabled: {type: Boolean, default: false},
      required: {type: Boolean, default: false},
      size: String
    },

    data() {
      return {
        url: `${process.env.API_URL_BASE}/commons/attachments/uploadTmp.do`
      }
    },

    computed: {
      fileList() {
        return _([this.value])
          .compact()
          .map(x => this.urlProp ? x[this.urlProp] : x)
          .map(filename => ({url: this.imageUrl(filename)}))
          .value();
      }
    },

    methods: {
      imageUrl(filename) {
        return `${process.env.API_URL_BASE}/files/${filename}`;
      },

      onSuccess(resp) {
        const filename = resp.data.data;
        this.$emit('input', this.urlProp ? {[this.urlProp]: filename} : filename);
      },

      onRemove() {
        this.$emit('input', null);
      },

      upload({action, filename, file, onSuccess}) {
        const form = new FormData();
        form.append(filename, file);
        axios.post(action, form).then(onSuccess)
      },
    }
  }
</script>

<style lang="scss">
  .app-single-image-upload {
    width: 100px!important;
    height: 100px!important;
    >div {
      height: 148px;
      position: relative;
      ul.el-upload-list--picture-card>li {
        z-index: 999;
      }

      .el-upload--picture-card {
        position: absolute;
        top: 0;
        left: 0;
        line-height: 100px!important;
        width: 100px!important;
        height: 100px!important;
      }
      .el-upload-list__item{
        width: 100px!important;
        height: 100px!important;
      }
      .el-upload-list__item-actions{
        width: 100px!important;
        height: 100px!important;
      }
    }
  }
</style>
